<template>
  <el-card>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图管理</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索表单 -->
    <el-form
      :inline="true"
      :model="swiperForm"
      class="demo-form-inline"
      size="large"
      style="margin-top: 25px"
    >
      <el-form-item label="跳转链接">
        <el-input v-model="swiperForm.link" placeholder="请输入跳转链接" />
      </el-form-item>
      <el-form-item label="图片alt">
        <el-input v-model="swiperForm.alt" placeholder="请输入图片alt" />
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="clear">清空</el-button>
        <el-button type="primary" @click="getSwiperListData">搜索</el-button>
        <el-button type="success" @click="dialogVisible = true">新增轮播图</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin-top: 12px">
    <el-table :data="swiperList" style="width: 100%">
      <el-table-column label="轮播图图片" prop="img">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 80px"
            :src="row.img"
            :preview-src-list="[row.img]"
            preview-teleported
          >
            <template #error>
              <div class="image-slot">
                <img v-error />
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="跳转地址" prop="link">
        <template #default="{ row }">
          <a :href="row.link" target="_blank" style="text-decoration: none; color: #606266">{{
            row.link
          }}</a>
        </template>
      </el-table-column>
      <el-table-column label="图片alt" prop="alt" />
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-switch :model-value="row.flag"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click="revise(row)">修改</el-button>
          <el-button type="danger" @click="del(row.bannerid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="swiperForm.page"
      v-model:page-size="swiperForm.pageSize"
      :page-sizes="[3, 4, 5, 6]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="mode === 'edit' ? '修改轮播图' : '新增轮播图'"
    width="50%"
  >
    <el-form :model="dialogForm" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="轮播图图片" prop="img" style="width: 85%">
        <!-- 文件上传 -->
        <el-upload
          :action="uploadUrl"
          v-model:file-list="fileList"
          :limit="1"
          list-type="picture-card"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePictureCardPreview"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="prevDialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="跳转链接" prop="link" style="width: 85%">
        <el-input v-model="dialogForm.link" />
      </el-form-item>
      <el-form-item label="alt说明" style="width: 85%">
        <el-input v-model="dialogForm.alt" />
      </el-form-item>
      <el-form-item label="启动/禁用">
        <el-switch v-model="dialogForm.flag" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onsubmit"> 确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getSwiperList, AddSwiper, updateSwiper, deleteSwiper } from '@/api/swiper'
import { swiper } from '@/types/swiper'
import { reactive, ref, watch } from 'vue'
import {
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
//table时需使用
const swiperList = ref<swiper[]>([])
const total = ref(0)
const swiperForm = ref({
  page: 1,
  pageSize: 3,
  link: '',
  alt: ''
})
const mode = ref('add')
const dialogVisible = ref(false)
const dialogForm = ref({
  bannerid: '',
  img: '',
  link: '',
  alt: '',
  flag: true
})
//带条件获取数据
const getSwiperListData = async () => {
  const res = await getSwiperList(swiperForm.value)
  swiperList.value = res.data.data.items
  total.value = res.data.data.total
}
getSwiperListData()
const clear = () => {
  swiperForm.value = {
    page: 1,
    pageSize: 3,
    link: '',
    alt: ''
  }
  getSwiperListData()
}
//每页条数改变
const handleSizeChange = (pageSize: number) => {
  swiperForm.value.pageSize = pageSize
  getSwiperListData()
}
//当前页发生改变
const handleCurrentChange = (page: number) => {
  swiperForm.value.page = page
  getSwiperListData()
}
//校验规则
const linkRule = (_, value, callback: (value?: string | Error) => void) => {
  const reg = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/
  if (reg.test(value)) {
    callback()
  } else {
    callback('跳转地址不合法！')
  }
}
const rules = reactive<FormRules>({
  img: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
  link: [
    { required: true, message: '链接不能为空', trigger: 'blur' },
    { validator: linkRule, trigger: 'blur' }
  ]
})
// 上传的地址
const uploadUrl = import.meta.env.VITE_BASE_URL + 'file/upload'
const fileList = ref<UploadUserFile[]>([])
//要预览的图片
const dialogImageUrl = ref('')
const prevDialogVisible = ref(false)
//上传前要处理的事
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件必须是jpg或png的类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小必须是2M一下')
    return false
  }
  return true
}
//点击预览是触发的事件
const handlePictureCardPreview: UploadProps['onPreview'] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!
  prevDialogVisible.value = true
}
//上传成功后要处理的事
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  dialogForm.value.img = response.fileUrl
  //对上传图片那一项进行单独校验
  formRef.value.validateField('img')
}
//删除上传图片要做到事
const handleRemove = () => {
  dialogForm.value.img = ''
  dialogImageUrl.value = ''
}
//当超出限制时，执行的钩子函数
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('文件只能上传一张！')
}
//确认，新增或修改轮播图
const formRef = ref<FormInstance>()
const onsubmit = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    try {
      if (mode.value === 'add') {
        delete dialogForm.value.bannerid
        await AddSwiper(dialogForm.value)
      } else {
        await updateSwiper(dialogForm.value)
      }
      dialogVisible.value = false
      ElMessage.success(mode.value === 'add' ? '添加成功' : '修改成功')
      if (mode.value === 'add') {
        swiperForm.value.page = 1
      }
      getSwiperListData()
    } catch (error) {
      console.log(error)
    }
  })
}
//修改轮播图
const revise = (val: swiper) => {
  dialogVisible.value = true
  mode.value = 'edit'
  //z展开是一层深拷贝
  dialogForm.value = { ...val }
  //完全深拷贝
  // dialogForm.value=JSON.parse(JSON.stringify(row))

  fileList.value.push({
    name: val.alt,
    url: val.img
  })
}
watch(dialogVisible, value => {
  if (!value) {
    mode.value = 'add'
    fileList.value = []
    //清空表单内容
    dialogForm.value = {
      bannerid: '',
      img: '',
      link: '',
      alt: '',
      flag: true
    }
    //清空表单验证
    formRef.value.resetFields()
  }
})
//删除轮播图
const del = async (val: string) => {
  ElMessageBox.confirm('确认删除吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      await deleteSwiper(val)
      swiperForm.value.page = 1
      getSwiperListData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled'
      })
    })
}
</script>

<style scoped lang="less">
.image-slot {
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  img {
    width: 90%;
    height: 90%;
    margin-top: 5px;
  }
}
</style>
